<template>
  <el-dialog title="添加退款" :visible.sync="visible" width="35%" class="refundsmain" :destroy-on-close="false"
    :show-close="false" :before-close="handleCloserefunds">
    <el-form :model="refundAdd" :rules="refundrules" ref="refundAdd" label-width="130px">
      <el-form-item label="后台单号" prop="xmbzNo">
        <el-input v-model.trim="refundAdd.xmbzNo" size="small" style="width:200px;margin-right: 5px;"
          onkeyup="value=value.replace(/[^\a-\z\A-\Z0-9]/g, '').slice(0,30)"
          onafterpaste="value=value.replace(/[^\a-\z\A-\Z0-9]/g, '').slice(0,30)"
          @change="searchGood(refundAdd.xmbzNo)"></el-input>
        <el-button type="primary" size="small" plain icon="el-icon-search"
          @click="searchGood(refundAdd.xmbzNo)">搜索</el-button>
      </el-form-item>
      <div v-if='shoplist && shoplist.length'>
        <el-form-item label="退款选项">
          <el-checkbox-group v-model="orderDetailIds" @change="getTotalprice" size="mini">
            <el-checkbox v-for="(item, index) in shoplist" v-show="item.categoryName != '服务费'" :key="index"
              :label="item.id" :value="item.id" name="type"
              style="word-break: break-all;word-wrap:break-word;white-space: inherit;"
              :disabled="!!item.refundIdentification">
              <el-tag effect="plain" class="mr-5" size="mini">{{ item.categoryName }}</el-tag>
              <span>{{ item.goodsName }}(规格：{{ item.goodsSpecs }},价格：{{ (item.totalPrice / 100).toFixed(2) }})</span>
              <el-tag class="ml-5" type="danger" size='small' v-if='item.refundIdentification'>
                {{ item.refundIdentification }}</el-tag>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>
      <el-form-item label="是否生产" prop="isProduction">
        <el-select v-model="refundAdd.isProduction" placeholder="请选择是否生产" size="small">
          <el-option :label="item.dictValue" :value="item.dictKey" v-for="(item, index) in productionList"
            :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="退款等级" prop="refundGrade">
        <RefundLevelSelect ref="RefundLevelSelect" v-model="refundAdd.refundGrade" size="small" placeholder="请选择退款等级"
          @loadedList="handleLoadedLevelList"></RefundLevelSelect>
      </el-form-item>
      <el-form-item label="退款原因" prop="refundReason">
        <RefundReasonSelect ref="RefundReasonSelect" v-model="refundAdd.refundReason" size="small"
          @change="onChangeStripe"></RefundReasonSelect>
      </el-form-item>
      <el-form-item label="退款类型" prop="refundType">
        <RefundTypeSelect ref="RefundTypeSelect" v-model="refundAdd.refundType" size="small" placeholder="请选择退款类型">
        </RefundTypeSelect>
      </el-form-item>
      <el-form-item label="蛋糕去向" prop="cakeWhereabouts">
        <CakeWhereSelect v-model="refundAdd.cakeWhereabouts" size="small" placeholder="请选择蛋糕去向"></CakeWhereSelect>
      </el-form-item>
      <el-form-item label="渠道类别" prop="channelTypeId">
        <ChannelTypeSelect ref="ChannelTypeSelect" v-model="refundAdd.channelTypeId" class="w-120" size="small" @change="refundAdd.channelId = ''" clearable></ChannelTypeSelect>
      </el-form-item>
      <el-form-item label="渠道" prop="channelId">
        <ChannelSelect ref="ChannelSelect" v-model="refundAdd.channelId" class="w-120" size="small" @visible-change="getchannelListAdd" filterable clearable></ChannelSelect>
      </el-form-item>
      <!-- <el-form-item label="退款方式:" prop="refundMode">
          <el-radio-group v-model="refundAdd.refundMode">
            <el-radio v-for="(item,index) in RefundModeList" :key="index" :label="item.dictKey">
              {{ item.dictValue }}
            </el-radio>
          </el-radio-group>
        </el-form-item>-->
      <el-form-item label="退款金额：" prop="refundMoney">
        <el-input v-model.trim="refundAdd.refundMoney" class="inputType" size="small" style="width:200px"
          onkeyup="value=value.replace(/[^\-?\d.]/g,'')" onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="赔偿规则" prop="compensationMethod">
        <el-radio-group v-model.trim="refundAdd.compensationMethod" prop="compensationMethod">
          <el-radio :label="item.dictKey" v-for="item in compensationList"
            @change="headleAddMethod(item.dictKey, refundAdd.refundMoney)">
            <span>{{ item.dictValue }}</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="赔偿金额">
        <el-input v-model.trim="cakeCompensatePriceAdd" class="inputType" size="small" style="width:100px"
          onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
          onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
      </el-form-item>
      <el-form-item label="诚意金">
        <el-input v-model.trim="refundAdd.sincerityGold" class="inputType" size="small" style="width:100px"
          onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
          onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
      </el-form-item>
      <el-form-item label="赠送蛋糕">
        <el-input v-model.trim="refundAdd.giveCakePrice" class="inputType" size="small" style="width:100px"
          onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
          onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
      </el-form-item>
      <el-form-item label="赠送礼品">
        <el-input v-model.trim="refundAdd.giveGiftPrice" class="inputType" size="small" style="width:100px"
          onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
          onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
      </el-form-item>
      <el-form-item label="申请原因" prop="applyReason">
        <el-input v-model.trim="refundAdd.applyReason" type="textarea" size="small" style="width:200px" maxlength="50"
          show-word-limit :autosize="{ minRows: 4, maxRows: 6 }"></el-input>
      </el-form-item>
      <el-form-item label="门店" prop="store">
        <el-input v-model.trim="refundAdd.store" type="textarea" size="small" style="width:200px" maxlength="30"
          show-word-limit :autosize="{ minRows: 4, maxRows: 6 }"></el-input>
      </el-form-item>
      <el-form-item label="退款二维码">
        <el-upload class="avatar-uploader" action="/api/xmbz-goods/file/upload" :data="{ tag: 'refund' }"
          :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="refundAdd.refundCode" :src="refundAdd.refundCode" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleRefundsubmit(refundAdd, 'refundAdd')">添加</el-button>
        <el-button @click="visible = false" size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  //接口
  CompensationMethod,
  AddRefund,
  IsProductionList,
  getGoodsByxmbzNo,
} from "@/api/workorder";

export default {
  components: {
  },
  data() {
    return {
      visible: false,
      loading: false,
      refundAdd: {
        refundCode: ''
      },
      refundrules: {
        xmbzNo: [
          {
            required: true,
            message: "后台单号为空",
            trigger: "change"
          }
        ],
        platformNo: [
          {
            required: true,
            message: "平台单号为空",
            trigger: "change"
          }
        ],
        refundReason: [
          {
            required: true,
            message: "请选择退款原因",
            trigger: "change"
          }
        ],
        channelTypeId: [
          {
            required: true,
            message: "请选择渠道类别",
            trigger: "change"
          }
        ],
        channelId: [
          {
            required: true,
            message: "请选择渠道",
            trigger: "change"
          }
        ],
        isProduction: [
          {
            required: true,
            message: "请选择是否生产",
            trigger: "blur"
          }
        ],
        cakeWhereabouts: [
          {
            required: true,
            message: "请选择蛋糕去向",
            trigger: "change"
          }
        ],
        refundType: [
          {
            required: true,
            message: "请输入退款类型",
            trigger: "change"
          }
        ],
        refundMode: [
          {
            required: true,
            message: "请选择退款方式",
            trigger: "change"
          }
        ],
        refundGrade: [
          {
            required: true,
            message: "请输入退款等级",
            trigger: "change"
          }
        ],
        fullRefund: [
          {
            required: true,
            message: "请选择全额退款",
            trigger: "change"
          }
        ],
        refundMoney: [
          {
            required: true,
            message: "金额不能为空",
            trigger: "change"
          }
        ],
        sincerityGold: [
          {
            required: true,
            message: "金额不能为空",
            trigger: "change"
          }
        ],
        applyReason: [
          {
            required: true,
            message: "请输入申请原因",
            trigger: "change",
            max: 200
          }
        ],
        compensationMethod: [
          {
            required: true,
            message: "请至少选择一个赔偿方式",
            trigger: "change"
          }
        ],
        store: [
          {
            required: true,
            message: "请输入平台门店",
            trigger: "change"
          }
        ]
      },
      shoplist: [], //选择蛋糕列表
      orderDetailIds: [], //
      productionList: [], //是否生产
      RefundTypeList: [],
      compensationList: [], //赔偿方式
      cakeCompensatePriceAdd: "",
    }
  },
  methods: {
    show() {
      this.initForm()
      this.visible = true
      this.$nextTick(() => {
        this.$refs.RefundLevelSelect && this.$refs.RefundLevelSelect.setSelectIndex(0);
      })
    },
    initForm() {
      this.refundAdd = {
        refundCode: ''
      }
      this.cakeCompensatePriceAdd = ""
      this.orderDetailIds = [];
      this.shoplist = [];
      this.$refs.refundAdd && this.$refs.refundAdd.clearValidate()
      // this.$refs.refundAdd && this.$refs.refundAdd.resetFields()
    },
    //退款蛋糕、配件、定制蛋糕数据
    searchGood(item) {
      if (item) {
        getGoodsByxmbzNo({
          xmbzNo: item
        }).then(res => {
          this.shoplist = res.data.data;
          if (res.data.data) {
            this.refundAdd.refundMoney = (
              res.data.data[0].orderTotalPrice / 100
            ).toFixed(2);
            if (res.data.data[0].store) {
              this.refundAdd.store = res.data.data[0].store;
            }
          }
          if (this.shoplist && this.shoplist.length > 0) {
            // 退货退款
            this.selectArray = this.shoplist.filter(item => {
              return item.categoryName !== '服务费'
            }).map(item => item.id) || []
          }
        });
      } else {
        this.$message.error("请输入后台单号!");
      }
    },
    handleCloserefunds(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
    },
    // 退款模块获取蛋糕价格
    getTotalprice(value) {
      this.getrefundAmount(value);
    },
    // 获取退款不同商品类型的蛋糕的价格
    getrefundAmount(value) {
      var arrlist = [];
      arrlist.push(value);
      if (value.length == 0) {
        this.refundCakePrice = "";
        this.refundForm.refundMoney = "";
      } else {
        let cakePrice = [];
        let cakeSumPrice = 0;
        const reducer = (accumulator, currentValue) =>
          accumulator + currentValue;
        this.shoplist.map(parent => {
          value.map((item, valueindex) => {
            if (item == parent.id) {
              cakePrice.push(parent.totalPrice);
            }
          });
        });
        cakeSumPrice = cakePrice.reduce(reducer); //退款金额
        this.refundCakePrice = (cakeSumPrice / 100).toFixed(2);
        this.refundAdd.refundMoney = (cakeSumPrice / 100).toFixed(2);
      }
    },
    isProductionList() {
      //是否生产
      IsProductionList("").then(response => {
        this.productionList = response.data.data;
      });
    },
    onChangeStripe(value) {
      if (value) {
        this.refundAdd.refundType = "";
        const selectedLabel = this.$refs.RefundReasonSelect.getSelectedLabel()
        this.getRefundTypeList(selectedLabel)
      } else {
        this.$message({
          type: "warning",
          message: "请先选择退款原因!"
        });
        return false;
      }
    },
    handleLoadedLevelList() {
      this.$refs.RefundLevelSelect.setSelectIndex(0);
    },
    getRefundTypeList(reasonType) {
      this.$refs.RefundTypeSelect && this.$refs.RefundTypeSelect.getList(reasonType);
    },
    getchannelListAdd() {
      //渠道
      if (!this.refundAdd.channelTypeId) {
        this.$message({
          type: "warning",
          message: "请先选择渠道类别!"
        });
        return false;
      } else {
        const ChannelTypeItem = this.$refs.ChannelTypeSelect.getSelectedItem();
        this.$refs.ChannelSelect.getList(ChannelTypeItem.id)
      }
    },
    headleAddMethod(item, goodsPrice) {
      if (item == "1") {
        if (goodsPrice) {
          this.cakeCompensatePriceAdd = goodsPrice;
        } else {
          this.cakeCompensatePriceAdd = 0;
        }
      } else if (item == "2") {
        if (goodsPrice) {
          this.cakeCompensatePriceAdd = goodsPrice / 2;
        } else {
          this.cakeCompensatePriceAdd = 0;
        }
      } else if (item == "6") {
        this.cakeCompensatePriceAdd = 0;
      }
    },
    // 主图开始上传
    handleAvatarSuccess(response) {
      this.refundAdd.refundCode = response.data;
      // this.refundAdd.refundCode = fileList[0].response
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("上传头像图片只能是 JPG 格式 与 png格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
    },
    handleRefundsubmit(refundAdd, refundAddName) {
      var refundMoneys = "";
      if (refundAdd.refundMode == 1) {
        refundMoneys = refundAdd.refundMoney;
      }
      if (refundAdd.refundMode == 2) {
        var cakePrice = this.cakeCompensatePrice;
        let array1 = [
          refundAdd.sincerityGold * 100,
          cakePrice * 100,
          refundAdd.giveGiftPrice * 100,
          refundAdd.giveCakePrice * 100
        ];
        const reducer = (accumulator, currentValue) =>
          accumulator + currentValue;
        if (refundAdd.compensationMethod == 1) {
          refundMoneys = (array1.reduce(reducer) / 100).toFixed(2); //退款金额
        } else if (refundAdd.compensationMethod == 2) {
          refundMoneys = (array1.reduce(reducer) / 100).toFixed(2); //退款金额
        } else {
          refundMoneys = (array1.reduce(reducer) / 100).toFixed(2); //退款金额
        }
      }
      this.$refs[refundAddName].validate(valid => {
        if (valid) {
          if (this.orderDetailIds.length == 0) {
            this.$message({
              message: "请选择需要退款的商品",
              type: "warning"
            });
            return false;
          } else {
            const refundAddData = {
              xmbzNo: this.refundAdd.xmbzNo,
              platformNo: this.refundAdd.platformNo,
              selectOrderDetailIds: this.orderDetailIds, //选中的订单明细id的集合
              noSelectOrderDetailIds: this.selectArray, //初始未选择的订单明细id的集合
              isProduction: this.refundAdd.isProduction, //是否生产
              cakeWhereabouts: this.refundAdd.cakeWhereabouts, // 蛋糕去向
              refundGrade: this.refundAdd.refundGrade, //退款等级
              refundReason: this.refundAdd.refundReason, //退款原因
              refundType: this.refundAdd.refundType, //退款类型
              refundMode: this.refundAdd.refundMode, //退款方式
              refundMoney: this.refundCakePrice, // 退款金额
              compensationMethod: this.refundAdd.compensationMethod, //赔偿方式
              sincerityGold: this.refundAdd.sincerityGold, //诚意金
              cakeCompensatePrice: this.cakeCompensatePriceAdd, //赠送的蛋糕价格
              giveCakePrice: this.refundAdd.giveCakePrice,
              giveGiftPrice: this.refundAdd.giveGiftPrice,
              applyReason: this.refundAdd.applyReason, //申请原因
              store: this.refundAdd.store, //门店
              refundCode: this.refundAdd.refundCode, //退款二维码
              channelTypeId: this.refundAdd.channelTypeId,
              channelId: this.refundAdd.channelId
            };
            AddRefund(refundAddData).then(() => {
              this.$message({
                type: "success",
                message: "提交成功!"
              });
              this.visible = false;
              this.$emit('submit');
            });
          }
        } else {
          this.$message({
            type: "warning",
            message: "填写相关提交内容!"
          });
          return false;
        }
      });
    },
    CompensationMethodList() {
      // ****备款状态
      CompensationMethod("").then(response => {
        this.compensationList = response.data.data;
      });
    },
  },
  created() {
    this.isProductionList()
    this.CompensationMethodList()
  },
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 10px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border: 1px solid #ddd;
  border-radius: 10px;
}</style>
